<template>
  <div class="treatment-chart">
    <div v-loading="loading" class="chart-container">
      <div ref="chartRef" class="chart"></div>
    </div>
    
    <!-- 图表说明 -->
    <div class="chart-legend">
      <div class="legend-item">
        <span class="legend-color" style="background: #409EFF;"></span>
        <span>治疗次数</span>
      </div>
      <div class="legend-item">
        <span class="legend-color" style="background: #67C23A;"></span>
        <span>完成次数</span>
      </div>
      <div class="legend-item">
        <span class="legend-color" style="background: #E6A23C;"></span>
        <span>完成率</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

interface TreatmentData {
  date: string
  total_treatments: number
  completed_treatments: number
  completion_rate: number
  avg_intensity: number
  mode_distribution: {
    mode: string
    count: number
  }[]
}

interface Props {
  data: TreatmentData[]
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chartInstance || !props.data?.length) return
  
  const dates = props.data.map(item => item.date)
  const totalTreatments = props.data.map(item => item.total_treatments)
  const completedTreatments = props.data.map(item => item.completed_treatments)
  const completionRates = props.data.map(item => item.completion_rate)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: (params: any[]) => {
        const date = params[0].axisValue
        let tooltip = `<div style="margin-bottom: 5px; font-weight: bold;">${date}</div>`
        
        params.forEach(param => {
          const color = param.color
          const name = param.seriesName
          const value = param.value
          const unit = name === '完成率' ? '%' : '次'
          
          tooltip += `
            <div style="margin: 2px 0;">
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>
              ${name}: <strong>${value}${unit}</strong>
            </div>
          `
        })
        
        return tooltip
      }
    },
    legend: {
      data: ['治疗次数', '完成次数', '完成率'],
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: dates,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          rotate: 45,
          formatter: (value: string) => {
            // 格式化日期显示
            const date = new Date(value)
            return `${date.getMonth() + 1}/${date.getDate()}`
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '治疗次数',
        min: 0,
        axisLabel: {
          formatter: '{value} 次'
        }
      },
      {
        type: 'value',
        name: '完成率',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '治疗次数',
        type: 'bar',
        yAxisIndex: 0,
        data: totalTreatments,
        itemStyle: {
          color: '#409EFF'
        },
        emphasis: {
          itemStyle: {
            color: '#66B1FF'
          }
        }
      },
      {
        name: '完成次数',
        type: 'bar',
        yAxisIndex: 0,
        data: completedTreatments,
        itemStyle: {
          color: '#67C23A'
        },
        emphasis: {
          itemStyle: {
            color: '#85CE61'
          }
        }
      },
      {
        name: '完成率',
        type: 'line',
        yAxisIndex: 1,
        data: completionRates,
        lineStyle: {
          color: '#E6A23C',
          width: 3
        },
        itemStyle: {
          color: '#E6A23C'
        },
        symbol: 'circle',
        symbolSize: 6,
        smooth: true
      }
    ],
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  } as any
  
  chartInstance.setOption(option, true)
}

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听数据变化
watch(() => props.data, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 监听加载状态
watch(() => props.loading, (loading) => {
  if (!loading) {
    nextTick(() => {
      updateChart()
    })
  }
})

onMounted(() => {
  nextTick(() => {
    initChart()
  })
  
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped lang="scss">
.treatment-chart {
  .chart-container {
    position: relative;
    
    .chart {
      width: 100%;
      height: 300px;
    }
  }
  
  .chart-legend {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 10px;
    
    .legend-item {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 12px;
      color: #606266;
      
      .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 2px;
      }
    }
  }
}
</style>